package com.wwwarehouse.taskcenter.fragment.job_point.step2.child;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.ItemInfoResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.TaskCenterCommon;
import com.wwwarehouse.taskcenter.eventbus_event.JobPointStateEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_BUSINESS_ID;

/**
 * Created by Jackie on 2017/10/27
 * 子作业点物的转换维度  选择添加方式  查看所有添加
 */

public class ChooseAddWayChildItemChangeByAllFragment extends CommonBasePagerFragment {
    private String mBusinessId;

    // 搜索排序相关条件
    private String mName = null;
    private String mSort = "create_time desc";

    private int mSelectedPosition = 2;

    private ArrayList<ItemInfoResponseBean.ItemDetailsBean> mItemDetailsList;

    private static final int REQUEST_GET_ITEM_INFO = 0;

    public static final String KEY_SEARCH_BY_NAME = "key_search_by_name";
    public static final String KEY_SEARCH_BY_SORT = "key_search_by_sort";

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        ((BaseCardDeskActivity) mActivity).showFilterBt();

        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        mItemDetailsList = new ArrayList<>();
    }

    private void initData() {
        Bundle bundle = getArguments();

        if (bundle != null) {
            mBusinessId = bundle.getString(KEY_BUSINESS_ID);
        }
    }

    private void initEvent() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDownPull() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            super.onDownPull();

            ((BaseCardDeskActivity) mActivity).hideFilterBt();
        }
    }

    @Override
    public void textNoRealChanged(String text) {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayChildItemChangeByAllFragment) {
                mName = text;

                // 搜索
                getItemInfo(mName, mSort);
            }
        }
    }

    @Override
    public void cancelClick() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayChildItemChangeByAllFragment) {
                mName = null;
                mSort = null;

                getItemInfo(mName, mSort);
            }
        }
    }

    @Override
    public void sortClick(View anchor) {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            if (peekFragment() instanceof ChooseAddWayChildItemChangeByAllFragment) {
                PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedPosition, new PopUpUtils.OnChoiceListener() {
                    @Override
                    public void onChoice(int position) {
                        mSelectedPosition = position;

                        switch (position) {
                            case 2:
                                mSort = "create_time desc";
                                break;
                            case 3:
                                mSort = "create_time asc";
                                break;
                            default:
                                break;
                        }

                        getItemInfo(mName, mSort);
                    }
                }, null, getString(R.string.sort_create_time_from_near_to_far), getString(R.string.sort_create_time_from_far_to_near));
            }
        }
    }

    @Override
    public void onRefreshListener() {
        if (TaskCenterCommon.getInstance().isDetails()) {

        } else {
            getItemInfo(mName, mSort);
        }
    }

    @Override
    public void onLoadSuccess(String data, int what) {
        switch (what) {
            case REQUEST_GET_ITEM_INFO:
                ItemInfoResponseBean itemInfoResponseBean = JSON.parseObject(data, ItemInfoResponseBean.class);
                ArrayList<ItemInfoResponseBean.ItemDetailsBean> itemDetailsList = (ArrayList<ItemInfoResponseBean.ItemDetailsBean>) itemInfoResponseBean.getList();

                try {
                    Bundle bundle = new Bundle();
                    bundle.putString(KEY_BUSINESS_ID, mBusinessId);
                    bundle.putString(KEY_SEARCH_BY_NAME, mName);
                    bundle.putString(KEY_SEARCH_BY_SORT, mSort);
                    setData(itemInfoResponseBean.getTotal(), 10, new ChooseAddWayChildItemChangeByAllDetailsFragment().getClass().getName(), bundle, itemDetailsList);

                    if (itemInfoResponseBean.getTotal() > 0) {
                        initConfirmBtn();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadError(String s) {
        toast(s);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseAddWayChildItemChangeByAllFragment) {
            if (TaskCenterCommon.getInstance().isDetails()) {
                mActivity.setTitle(R.string.view_details);
            } else {
                if (TaskCenterCommon.getInstance().isStart()) {
                    mActivity.setTitle(R.string.choose_start_value);
                } else {
                    mActivity.setTitle(R.string.choose_end_value);
                }
            }
        }
    }

    @Override
    public void requestDatas() {
        super.requestDatas();

        if (TaskCenterCommon.getInstance().isDetails()) {
            if (TaskCenterCommon.getInstance().isStart()) {
                for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseStartMap()) {
                    ItemInfoResponseBean.ItemDetailsBean itemDetailsBean = new ItemInfoResponseBean.ItemDetailsBean();

                    String[] keys = taskCenterBean.getKey().split("\\+");

                    itemDetailsBean.setAbstractObjectUkid(keys[0]);
                    itemDetailsBean.setCount(Integer.parseInt(keys[1]));
                    itemDetailsBean.setUnitName(keys[2]);
                    itemDetailsBean.setName(taskCenterBean.getValue());
                    itemDetailsBean.setSelect(true);

                    mItemDetailsList.add(itemDetailsBean);
                }
            } else {
                for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseEndMap()) {
                    ItemInfoResponseBean.ItemDetailsBean itemDetailsBean = new ItemInfoResponseBean.ItemDetailsBean();

                    String[] keys = taskCenterBean.getKey().split("\\+");

                    itemDetailsBean.setAbstractObjectUkid(keys[0]);
                    itemDetailsBean.setCount(Integer.parseInt(keys[1]));
                    itemDetailsBean.setUnitName(keys[2]);
                    itemDetailsBean.setName(taskCenterBean.getValue());
                    itemDetailsBean.setSelect(true);

                    mItemDetailsList.add(itemDetailsBean);
                }
            }

            try {
                Bundle bundle = new Bundle();
                bundle.putString(KEY_BUSINESS_ID, mBusinessId);
                bundle.putString(KEY_SEARCH_BY_NAME, mName);
                bundle.putString(KEY_SEARCH_BY_SORT, mSort);
                setData(mItemDetailsList.size(), 10, new ChooseAddWayChildCombinationByAllDetailsFragment().getClass().getName(), bundle, mItemDetailsList);

                //有结果才显示确定按钮
                if (mItemDetailsList.size() > 0) {
                    initConfirmBtn();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            getItemInfo(mName, mSort);
        }
    }

    public void onEventMainThread(JobPointStateEvent event) {
        if (peekFragment() instanceof ChooseAddWayChildItemChangeByAllFragment) {
            if (TaskCenterCommon.getInstance().isDetails()) {
                for (ItemInfoResponseBean.ItemDetailsBean itemDetailsBean : mItemDetailsList) {
                    if (itemDetailsBean.isSelect()) {
                        mConfirmBtn.setEnabled(true);

                        return;
                    }
                }

                mConfirmBtn.setEnabled(false);
            } else {
                if (event.getSelectObject() instanceof ItemInfoResponseBean.ItemDetailsBean) {
                    ItemInfoResponseBean.ItemDetailsBean itemDetailsBean = (ItemInfoResponseBean.ItemDetailsBean) event.getSelectObject();

                    if (itemDetailsBean.isSelect()) {
                        mItemDetailsList.add(itemDetailsBean);
                    } else {
                        mItemDetailsList.remove(itemDetailsBean);
                    }
                }

                if (mItemDetailsList.size() > 0) {
                    mConfirmBtn.setEnabled(true);
                } else {
                    mConfirmBtn.setEnabled(false);
                }
            }
        }
    }

    /**
     * 查询概念物
     */
    private void getItemInfo(String name, String sort) {
        Map map = new HashMap();

        map.put("name", name);
        map.put("ownerUkid", mBusinessId);
        map.put("page", 1);
        map.put("size", 10);
        map.put("sort", sort);
        map.put("type", "H_GOODS");

        loadData(TaskCenterConstant.URL_GET_ITEM_INFO, map, REQUEST_GET_ITEM_INFO);
    }

    private void initConfirmBtn() {
        showConfirmButton();

        if (TaskCenterCommon.getInstance().isDetails()) {
            mConfirmBtn.setEnabled(true);
        } else {
            mConfirmBtn.setEnabled(false);
        }

        setConfirmBtnText(mActivity.getString(R.string.confirm));

        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TaskCenterCommon.getInstance().isDetails()) {
                    popFragment();

                    buildItemChangeMap(mItemDetailsList);

                    // 反向传值
                    Intent intent = new Intent("ChooseAddWayChildItemChangeByAll");
                    mActivity.sendBroadcast(intent);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("selectList", mItemDetailsList);

                    ChooseAddWayChildItemChangeByAllSetNumPageFragment chooseAddWayChildItemChangeByAllSetNumPageFragment = new ChooseAddWayChildItemChangeByAllSetNumPageFragment();
                    chooseAddWayChildItemChangeByAllSetNumPageFragment.setArguments(bundle);
                    pushFragment(chooseAddWayChildItemChangeByAllSetNumPageFragment);
                }
            }
        });
    }

    private void buildItemChangeMap(List<ItemInfoResponseBean.ItemDetailsBean> itemDetailsList) {
        Map map = new HashMap();
        List<Map<String, String>> list = new ArrayList<>();

        for (ItemInfoResponseBean. ItemDetailsBean itemDetailsBean : itemDetailsList) {
            if (itemDetailsBean.isSelect() && itemDetailsBean.getCount() > 0) {
                Map<String, String> listMap = new HashMap<>();

                listMap.put("key", itemDetailsBean.getAbstractObjectUkid() + "+" + itemDetailsBean.getCount() + "+" + itemDetailsBean.getUnitUkid());
                listMap.put("value", itemDetailsBean.getName());

                list.add(listMap);
            }
        }

        map.put("list", list);
        map.put("type", "ITEM");

        if (TaskCenterCommon.getInstance().isStart()) {
            TaskCenterCommon.getInstance().setStartMap(map);
        } else {
            TaskCenterCommon.getInstance().setEndMap(map);
        }
    }
}
